What do you think is the usual meaning of
1 + 2 * 3 ?
Usually 1 + 2 * 3
means to do the multiplication first.
To clear up these problems, arithmetic operators have each been given a priority. When there is a choice, do the highest priority operation first. The priorities of operators is given in the table. The highest priority is "1" and the lowest is "4".
operator |
meaning | priority |
---|---|---|
^ |
power | 1 |
- |
negation | 2 |
* |
multiply | 3 |
/ |
divide | 3 |
+ |
addition | 4 |
- |
subtraction | 4 |
For example:
1 + 2 * 3 ------- * has higher priority than +, so do first = 1 + 6 = 7
Do this:
2 * 3 + 1